#!/bin/bash -xe

source $(dirname $0)/env.sh

if [ ! -e $LINUX_KERNEL_IMAGE ]; then
    cd $LINUX_KERNEL_DIR
    make CROSS_COMPILE=$TOOLCHAIN ARCH=$LINUX_KERNEL_ARCH $LINUX_KERNEL_DEFCONFIG
    make CROSS_COMPILE=$TOOLCHAIN ARCH=$LINUX_KERNEL_ARCH -j8
    cd -
fi

if [ ! -e $BUSYBOX_OUT_DIR ]; then
    cd $BUSYBOX_DIR
    make defconfig
    make CROSS_COMPILE=$TOOLCHAIN -j8
    make install CROSS_COMPILE=$TOOLCHAIN -j8
    cd -
    mv $BUSYBOX_OLD_OUT_DIR $BUSYBOX_OUT_DIR
fi

if [ ! -e $BASH_OUT_DIR ]; then
    mkdir -p $BASH_OUT_DIR
    cd $BASH_OUT_DIR
    prefix=$(pwd)
    cd -

    cd $BASH_DIR
    ./configure \
        --prefix=$prefix \
        --target=$CONFIGURE_TOOLCHAIN \
        --host=$CONFIGURE_TOOLCHAIN \
        CC=${CONFIGURE_TOOLCHAIN}-gcc \
        AR=${CONFIGURE_TOOLCHAIN}-ar || (rm -rf $BASH_OUT_DIR; exit 1)
    make
    make install
    cd -
fi
